﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;

using UnityScriptEngine;

using DataManager;
using StoreClientModule;

namespace MBB_Store_Sales_Report
{
    public partial class frmExpensesList : Form
    {
        UnityProcessor proc = new UnityProcessor();
        Threader t = new Threader();
        UnityScript[] dat = new UnityScript[0];

        string dateFilter;
        string[] arrDate;
        string myDay;
        string myMonth;
        string myYear;
        string filter;

        float totalA = 0.0f, totalB = 0.0f;
        float gtotalA = 0.0f, gtotalB = 0.0f;

        DataTable RecordTable = new DataTable();
        DataTable dt = new DataTable();
        DataTable recordedDates = new DataTable();
        //ExpensesRecords er = new ExpensesRecords();
        
        int pp = 1;
        int cnt = 0;

        public frmExpensesList()
        {
            InitializeComponent();
           
            btnView.Click += new EventHandler(btnView_Click);
            btnClose.Click += new EventHandler(btnClose_Click);
            panel2.EnabledChanged += new EventHandler(panel2_EnabledChanged);
           
           // grd.MouseClick += new MouseEventHandler(grd_MouseClick);
           // er.ProcessError += new ExpensesRecords.MyEventHandler(er_ProcessError);
           // er.ProcessCompleted += new ExpensesRecords.MyEventHandler(er_ProcessCompleted);
           //editToolStripMenuItem.Click += new EventHandler(editToolStripMenuItem_Click);
           
            proc.ProcessCompleted += new ProcessHandler(proc_ProcessCompleted);
            proc.ProcessError +=new ProcessHandler(proc_ProcessError);
            t.MethodCompleted += new EventHandler(t_MethodCompleted);
            btnPrint.Click += new EventHandler(btnPrint_Click);
        }

        void CreateDataTable()
        {
            if (filter.Equals("Month"))
            {
                dt = new DataTable();
                dt.Columns.Add("Date");
                dt.Columns.Add("Category A Total Amount");
                dt.Columns.Add("Category B Total Amount");


                for (int i = 0; i < recordedDates.Rows.Count; i++)
                {
                    totalA = 0.0f;
                    totalB = 0.0f;

                    string onTestDate = recordedDates.Rows[i]["fDate"].ToString();
                    DataRow dr = dt.NewRow();
                    dr["Date"] = DateTime.Parse(onTestDate).ToString("MM-dd-yyyy");

                    for (int j = 0; j < RecordTable.Rows.Count; j++)
                    {
                        string date = RecordTable.Rows[j]["fDate"].ToString();
                        if (onTestDate.Equals(date))
                        {
                            string cat = RecordTable.Rows[j]["fExpensesType"].ToString();
                            float amount = float.Parse(RecordTable.Rows[j]["fExpensesAmount"].ToString());

                            if (cat.Equals("A"))
                            {
                                totalA += amount;
                            }
                            else if (cat.Equals("B"))
                            {
                                totalB += amount;
                            }
                        }
                    }

                    dr["Category A Total Amount"] = totalA.ToString("#,#0.00");
                    dr["Category B Total Amount"] = totalB.ToString("#,#0.00");
                    dt.Rows.Add(dr);
                }
                dt.DefaultView.Sort = "Date";
                
            }
            else
            {
                dt = RecordTable;
            }
        }

        void t_MethodCompleted(object sender, EventArgs e)
        {
            t.SafeCall(this, delegate
            {
                switch (sender.ToString())
                {
                    case "CreateDataTable":
                        grd.DataSource = dt;
                        
                        if (filter.Equals("Month"))
                        {
                            grd.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                        }
                        else
                        {
                            grd.Columns[0].HeaderText = "Date";
                            grd.Columns[1].HeaderText = "Description";
                            grd.Columns[2].HeaderText = "Amount";
                            grd.Columns[3].HeaderText = "Category";

                            
                        }
                        grd.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                        computeGrandTotalPerCategory();
                        this.Enabled = true;
                        
                        break;
                }
            });
        }
        void computeGrandTotalPerCategory()
        {
            gtotalA = 0;
            gtotalB = 0;

            for (int i = 0; i < grd.Rows.Count; i++)
            {
                if (filter.Equals("Day"))
                {
                    if (grd.Rows[i].Cells[3].Value.ToString().Equals("A"))
                    {
                        gtotalA += float.Parse(grd.Rows[i].Cells[2].Value.ToString());
                    }
                    else
                    {
                        gtotalB += float.Parse(grd.Rows[i].Cells[2].Value.ToString());
                    }
                }
                else if (filter.Equals("Month"))
                {
                    gtotalA += float.Parse(grd.Rows[i].Cells[1].Value.ToString());
                    gtotalB += float.Parse(grd.Rows[i].Cells[2].Value.ToString());
                }
            }

            txtA.Text = gtotalA.ToString("#,#0.00");
            txtB.Text = gtotalB.ToString("#,#0.00");
        }
        void proc_ProcessError(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                MessageBox.Show(desc);
            });
        }
        void proc_ProcessCompleted(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                switch (id)
                {
                  
                    case "SEARCH":
                        proc.DBPUX_Data_Fetch(out dat);
                        RecordTable = dat[0].ToDataTable();
                        recordedDates = dat[1].ToDataTable();
                        t.MethodCall(CreateDataTable);
                        break;
                }
            });
        }

        
        void btnPrint_Click(object sender, EventArgs e)
        {
            PrintDocument pd = new PrintDocument();
            pd.DocumentName = lblText.Text;
            pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
            PrintDialog pdlg = new PrintDialog();
            pdlg.Document = pd;
            if (pdlg.ShowDialog() == DialogResult.OK)
            {
                PrintPreviewDialog ppdlg = new PrintPreviewDialog();
                ppdlg.Document = pd;
                //Tracking.EnterLog("Price Table is printed.", DateTime.Now.ToString());
                ppdlg.ShowDialog();
            }
        }

        void pd_PrintPage(object sender, PrintPageEventArgs e)
        {
            float lpp = 0;
            float y = 0, y2=0, tmp = 0;
            float tm = e.MarginBounds.Top;
            float lm = e.MarginBounds.Left;
            float rm = e.PageBounds.Width - 100;
            float bm = e.PageBounds.Height - 100;
            float ht = 0;
            Font cFont;
            StringFormat sf = new StringFormat();
            float tmpStx = 0;
            float totalA = 0.0f, totalB = 0.0f;
            //Header
            y = 150;
            y2 = 150;

            cFont = new Font("Courier New", 12f, FontStyle.Bold);
            ht = cFont.GetHeight(e.Graphics);
            sf.Alignment = StringAlignment.Center;
            e.Graphics.DrawString(Common.lStoreName, new Font("Courier New", 15f, FontStyle.Bold), Brushes.Black, e.PageBounds.Width / 2, 50, sf);
            e.Graphics.DrawString(Common.lStoreAddress, new Font("Courier New", 15f, FontStyle.Bold), Brushes.Black, e.PageBounds.Width / 2, 70, sf);


            float stx = 0, stx2 = 0;

            if (filter.Equals("Day"))
            {
                e.Graphics.DrawString("Expenses for "+txtDate.Text, new Font("Courier New", 15f, FontStyle.Bold), Brushes.Black, e.PageBounds.Width / 2, 90, sf);
                cFont = new Font("Courier New", 10f, FontStyle.Regular);
                sf.Alignment = StringAlignment.Far;
                e.Graphics.DrawString("Printed Date: "+DateTime.Now.ToShortDateString(), cFont, Brushes.Black, rm, y, sf);
                //Column Header
                
                y += ht;
                y2 += ht;
                e.Graphics.FillRectangle(Brushes.LightGray, lm, y, rm - lm, ht);
                e.Graphics.DrawRectangle(new Pen(Brushes.Black), lm, y, rm - lm, ht);

                sf.Alignment = StringAlignment.Center;
                float cx = lm + (((rm - lm) * 30) / 100);
                float tx = lm + (((rm - lm) * 15f) / 100);
                e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
                e.Graphics.DrawString("Expenses A", cFont, Brushes.Black, tx, y, sf);

                cx += ((rm - lm) * 20) / 100;
                tx = cx - ((rm - lm) * 20) / 200;
                e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
                e.Graphics.DrawString("Amount", cFont, Brushes.Black, tx, y, sf);

                cx += ((rm - lm) * 30) / 100;
                tx = cx - ((rm - lm) * 30) / 200;
                e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
                e.Graphics.DrawString("Expenses B", cFont, Brushes.Black, tx, y, sf);

                tx += ((rm - lm) * 20) / 100;
                e.Graphics.DrawString("Amount", cFont, Brushes.Black, tx + 25, y, sf);

                //Data

                y += ht * (1.5f);
                y2 += ht * (1.5f);
                ht = cFont.GetHeight(e.Graphics);
                lpp = (bm - y) / ht;
                int cl = 0;
                

                while (cl <= lpp && cnt < grd.Rows.Count)
                {
                    sf.Alignment = StringAlignment.Near;
                    stx = lm + 1;
                    stx2 = lm + ((rm - lm) * 51) / 100;

                    if (grd.Rows[cnt].Cells[3].Value.ToString().Equals("A"))
                    {
                        string str = grd.Rows[cnt].Cells[1].Value.ToString();
                        if (str.Length > 23)
                            str = str.Substring(0, 19) + "...";
                        e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);

                        sf.Alignment = StringAlignment.Far;
                        stx += ((rm - lm) * 49) / 100;
                        str = grd.Rows[cnt].Cells[2].Value.ToString();
                        e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);
                        y += ht;

                        //totalA += float.Parse(str);
                    }
                    else
                    {
                        string str = grd.Rows[cnt].Cells[1].Value.ToString();
                        if (str.Length > 23)
                            str = str.Substring(0, 19) + "...";
                        e.Graphics.DrawString(str, cFont, Brushes.Black, stx2, y2, sf);

                        sf.Alignment = StringAlignment.Far;
                        stx2 += ((rm - lm) * 49) / 100;
                        str = grd.Rows[cnt].Cells[2].Value.ToString();
                        e.Graphics.DrawString(str, cFont, Brushes.Black, stx2, y2, sf);
                        y2 += ht;

                        //totalB += float.Parse(str);
                    }

                    cnt++;
                    cl++;
                }

                if (y2 >= y)
                {
                    tmp = y2;
                    tmpStx = stx2;
                }
                else
                {
                    tmp = y;
                    tmpStx = stx;
                }
            }
            else
            {

                e.Graphics.DrawString("Expenses for the month of " + DateTime.Parse(txtDate.Text).ToString("MMMM") + " - " + myYear, new Font("Courier New", 15f, FontStyle.Bold), Brushes.Black, e.PageBounds.Width / 2, 90, sf);
                cFont = new Font("Courier New", 10f, FontStyle.Regular);
                sf.Alignment = StringAlignment.Far;
                e.Graphics.DrawString("Printed Date: " + DateTime.Now.ToShortDateString(), cFont, Brushes.Black, rm, y, sf);
                
                //Column Header
                //float stx = 0, stx2 = 0;
                y += ht;
                y2 += ht;

                e.Graphics.FillRectangle(Brushes.LightGray, lm, y, rm - lm, ht);
                e.Graphics.DrawRectangle(new Pen(Brushes.Black), lm, y, rm - lm, ht);

                cFont = new Font("Courier New", 11f, FontStyle.Regular);

                sf.Alignment = StringAlignment.Center;
                float cx = lm + (((rm - lm) * 30) / 100);
                float tx = lm + (((rm - lm) * 15f) / 100);
                e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
                e.Graphics.DrawString("Date", cFont, Brushes.Black, tx, y, sf);

                cx += ((rm - lm) * 35) / 100;
                tx = cx - ((rm - lm) * 35) / 200;
                e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
                e.Graphics.DrawString("Category A - Amount", cFont, Brushes.Black, tx, y, sf);

                cx += ((rm - lm) * 35) / 100;
                tx = cx - ((rm - lm) * 35) / 200;
                e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
                e.Graphics.DrawString("Category B - Amount", cFont, Brushes.Black, tx, y, sf);

                //Data

                y += ht * (1.5f);
                //y2 += ht * (1.5f);
                ht = cFont.GetHeight(e.Graphics);
                lpp = (bm - y) / ht;
                int cl = 0;
                //float stx = 0;
                //, stx2 = 0;

                while (cl <= lpp && cnt < grd.Rows.Count)
                {
                    sf.Alignment = StringAlignment.Near;
                    stx = lm + 1;
                    //stx2 = lm + ((rm - lm) * 51) / 100;

                    e.Graphics.DrawString(grd.Rows[cnt].Cells[0].Value.ToString(), cFont, Brushes.Black, stx, y, sf);
                    sf.Alignment = StringAlignment.Far;
                    stx += ((rm - lm) * 64) / 100;
                    e.Graphics.DrawString(grd.Rows[cnt].Cells[1].Value.ToString(), cFont, Brushes.Black, stx, y, sf);
                    stx += ((rm - lm) * 34) / 100;
                    e.Graphics.DrawString(grd.Rows[cnt].Cells[2].Value.ToString(), cFont, Brushes.Black, stx, y, sf);
                    y += ht;

                    cnt++;
                    cl++;
                }
            }

            if (cnt < grd.Rows.Count)
            {
                e.HasMorePages = true;
                pp++;
            }
            else
            {
                y += ht;
                if (filter.Equals("Day"))
                {
                    sf.Alignment = StringAlignment.Near;
                    e.Graphics.DrawString("Total", cFont, Brushes.Blue, lm + 1, tmp, sf);
                    sf.Alignment = StringAlignment.Far;
                    tmpStx = lm + ((rm - lm) * 49) / 100;
                    e.Graphics.DrawString(txtA.Text, cFont, Brushes.Blue, tmpStx, tmp, sf);

                    sf.Alignment = StringAlignment.Near;
                    e.Graphics.DrawString("Total", cFont, Brushes.Blue, lm + 1 + ((rm - lm) * 51) / 100, tmp, sf);
                    sf.Alignment = StringAlignment.Far;
                    tmpStx += ((rm - lm) * 50) / 100;
                    e.Graphics.DrawString(txtB.Text, cFont, Brushes.Blue, tmpStx + 2, tmp, sf);
                }
                else
                {
                    sf.Alignment = StringAlignment.Far;
                    
                    e.Graphics.DrawString(txtA.Text, cFont, Brushes.Black, lm + 417, y, sf);
                    
                    e.Graphics.DrawString(txtB.Text, cFont, Brushes.Black, lm + 638, y, sf);
                    y += ht;
                }
                e.HasMorePages = false;
                cnt = 0;
                pp = 1;
            }
              
        }

        void btnView_Click(object sender, EventArgs e)
        {
            this.Enabled = false;
            dateFilter = txtDate.Text;
            arrDate = dateFilter.Split('/');
            myDay = int.Parse(arrDate[1].Trim()).ToString();
            myMonth = int.Parse(arrDate[0].Trim()).ToString();
            myYear = int.Parse(arrDate[2].Trim()).ToString();
            filter = cmbType.Text;
            Search();
        }
        void Search()
        {
            while (proc.IsRunning){  }
            proc.ProcStart();
            UnityScript u = new UnityScript("SEARCH", 4);

            u.Script_Add(Script.DBPUX_BEGIN);
            string sql = "";
            switch (filter)
            {
                case "Day":
                    sql = " fDate = '" + txtDate.Text + "'";
                    break;
                case "Month":
                    sql = " fDate LIKE '" + myMonth + "%" + myYear + "'";
                    break;
            }
            u.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT fID, fDate, fExpensesName, fExpensesAmount, fExpensesType, fStamp FROM tblexpenses WHERE (" + sql + ")"));
            u.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT DISTINCT fDate FROM tblexpenses WHERE (" + sql + ")"));
            
            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);
        }



        //obsolete methods
        /*
        void editToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (grd.SelectedRows.Count == 1)
            {
                ExpensesEntryCommit expenses = new ExpensesEntryCommit();
                //pass to the struct
                expenses.id = grd.SelectedRows[0].Cells[0].Value.ToString();
                expenses.name = grd.SelectedRows[0].Cells[1].Value.ToString();
                expenses.amount = grd.SelectedRows[0].Cells[2].Value.ToString();
                expenses.type = grd.SelectedRows[0].Cells[3].Value.ToString();
                expenses.date = txtDate.Text;
                //then pass the struct to the parent (form 1)
                Common.parent.EditExpenses(expenses);
            }
        }
        void grd_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right && grd.SelectedRows.Count == 1)
            {
                grd.ContextMenuStrip = popup;
            }
        }
        void er_ProcessCompleted(string msg)
        {
            uCoreClasses.uThreader t = new uCoreClasses.uThreader();
            t.SafeCall(this, delegate
            {
                if (er.ProcessCode == 3)
                {
                    RecordTable = er.RecordTable;
                    
                    grd.DataSource = RecordTable;
                    grd.Columns["Code"].Visible = false;
                    computeTotal();
                }

            });
        }
        void er_ProcessError(string msg)
        {
            uCoreClasses.uThreader t = new uCoreClasses.uThreader();
            t.SafeCall(this, delegate
            {
                MessageBox.Show(msg);
            });
        }

        void computeTotal()
        {
            double tAmount = 0.0f;
            for (int i = 0; i < grd.Rows.Count; i++)
            {
                double amt = 0.0f;
                double.TryParse(grd.Rows[i].Cells[2].Value.ToString(), out amt);
                tAmount = tAmount + amt;
            }
            txtTotal.Text = Common.FormatCurrency(tAmount);
        }
        */
        
        void panel2_EnabledChanged(object sender, EventArgs e)
        {
            if (!panel2.Enabled)
            {
                panel2.BackColor = Color.MidnightBlue;
            }
            else
            {
                panel2.BackColor = Color.RoyalBlue;
            }
        }
        void btnClose_Click(object sender, EventArgs e)
        {
            pnlExpensesListOnline.Dispose();
            this.Dispose();
        }
        public Panel PanelForm
        {
            get { return pnlExpensesListOnline; }
        }
        public void Initialize(string Title)
        {
            this.Select();
            lblText.Text = Title;
            cmbType.SelectedIndex = 0;
        }
    }
}
